package com.photoeditor.demo.ui.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.common.base.ui.widget.image.RoundImageView;
import com.common.base.utils.thread.ThreadPool;
import com.photoeditor.R;
import com.photoeditor.demo.db.FilterConstant;
import com.photoeditor.demo.model.store.download.DownloadUtils;
import com.photoeditor.demo.model.store.download.IDownloadListener;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.util.font.FontHelper;

import java.lang.ref.WeakReference;

/**
 * Created by winn on 17/10/17.
 */

public class FontListItem extends RelativeLayout {

    public View mSelView;
    public ImageView mIcon;
    public CircleFillProgressView mProgress;
    public ImageView mDownloadTipIcon;

    private IDownloadListener mDownloadListener;
    public StoreOnlineBean mFontBean;

    public FontListItem(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.item_fontlist, this, true);
        mIcon = (RoundImageView) findViewById(R.id.iv_icon);
        mProgress = (CircleFillProgressView) findViewById(R.id.progress_view);
        mSelView = findViewById(R.id.sel_effect);
        mDownloadTipIcon = findViewById(R.id.iv_download_icon);
        if (isHardwareAccelerated()) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
    }

    public void updateData(StoreOnlineBean bean, boolean sel) {
        mFontBean = bean;
        FontHelper.loadFontIcon(bean, mIcon);
        if (sel) {
            mSelView.setVisibility(VISIBLE);
        } else {
            mSelView.setVisibility(GONE);
        }
        statistic(bean);
    }

    private void statistic(StoreOnlineBean bean) {
        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_FONT_BAR_DISPLAY,
                StatisticsConstant.UMENG_CUSTOM_EVENT_KEY_SHOW, bean.getPkgName());
    }

    public void setSel(boolean sel) {
        if (sel) {
            mSelView.setVisibility(VISIBLE);
        } else {
            mSelView.setVisibility(GONE);
        }
    }

    public void updateProgress(int percentage) {
        if (percentage == 0) {
            percentage = 1;
        }
        if (percentage < 0) {
            // 未下载状态
            mProgress.setProgress(0);
            mDownloadTipIcon.setVisibility(VISIBLE);
        } else if (percentage >= 0 && percentage < 100) {
            // 下载中
            mProgress.setProgress(percentage);
            mDownloadTipIcon.setVisibility(GONE);
        } else if (percentage >= 100) {
            // 下载完成
            mProgress.setVisibility(GONE);
            mDownloadTipIcon.setVisibility(GONE);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mFontBean.getType() != FilterConstant.TYPE_BUILDIN && !FontHelper.hasDownload(mFontBean)) {
            mProgress.setVisibility(VISIBLE);
            mDownloadTipIcon.setVisibility(VISIBLE);
            if (mFontBean != null) {
                String packageName = mFontBean.getPkgName();
                if (mDownloadListener == null) {
                    mDownloadListener = createNewListener();
                } else {
                    DownloadUtils.getInstance().removeListener(mDownloadListener);
                    mDownloadListener = createNewListener();
                }
                DownloadUtils.getInstance().addListener(mDownloadListener);
                if (FontHelper.hasDownload(mFontBean)) {
                    updateProgress(100);
                } else if (DownloadUtils.getInstance().getDownloadStatus(packageName) == DownloadUtils.DOWNLOAD_DEFAULT) {
                    updateProgress(-1);
                } else {
                    int percentage = DownloadUtils.getInstance().getPercentage(packageName);
                    updateProgress(percentage);
                }
            }
        } else {
            mProgress.setVisibility(GONE);
            mDownloadTipIcon.setVisibility(GONE);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        DownloadUtils.getInstance().removeListener(mDownloadListener);
    }

    private IDownloadListener createNewListener() {
        return new DownloadListener(mFontBean.getPkgName(), this);
    }

    private static class DownloadListener implements IDownloadListener {
        private String mDownloadId;
        private WeakReference<FontListItem> mRef;

        public DownloadListener(String downloadId, FontListItem view) {
            mDownloadId = downloadId;
            mRef = new WeakReference<>(view);
        }

        @Override
        public String getDownloadId() {
            return mDownloadId;
        }

        @Override
        public void onProgressUpdate(final String downloadId, final int progress) {
            if (!TextUtils.isEmpty(downloadId) && mDownloadId.equals(downloadId)) {
                if (mRef != null && mRef.get() != null) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            mRef.get().updateProgress(progress);
                        }
                    });
                }
            }
        }

        @Override
        public void onFailed(final String downloadId) {
            if (!TextUtils.isEmpty(downloadId) && mDownloadId.equals(downloadId)) {
                if (mRef != null && mRef.get() != null) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mRef.get().getContext(),
                                    mRef.get().getContext().getResources().getString(R.string.filter_download_failed), Toast.LENGTH_SHORT).show();
                            mRef.get().updateProgress(-1);
                        }
                    });
                }
            }
        }

        @Override
        public String getFullActivityName() {
            return "";
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
                | Paint.FILTER_BITMAP_FLAG));
        super.dispatchDraw(canvas);
    }
}
